<template>
	<div class="custom-column-container">
		<el-dialog
			:key="dialog.key"
			v-model="dialog.open"
			:title="title ? title : '自定义列'"
			class="custom-table-class"
			width="500px"
			:close-on-click-modal="false"
			append-to-body
			@closed="handlerClosed"
		>
			<el-row :gutter="20">
				<el-col :span="24">
					<draggable
						v-model="options"
						handle=".can-move"
						animation="500"
						ghost-class="ghost-cls"
						chosen-class="chosen-cls"
						drag-class="drag-cls"
						item-key="prop"
						@sort="handleSortChange"
					>
						<template #item="{ element: option }">
							<div
								style="margin-bottom: 6px"
								:style="{
									border: option.label === '' ? '1px solid red' : '1px solid #00ffff',
								}"
							>
								<el-input
									v-model="option.label"
									:class="[{ shake: option.label === '' && shakeAnimation }]"
									size="small"
									maxlength="30"
									show-word-limit
									placeholder="请输入列名，不能为空"
								>
									<template #prepend>
										<el-row style="width: 60px; text-align: center">
											<el-col :span="8">
												<i class="el-icon-rank can-move"></i>
											</el-col>
											<el-col :span="8">
												<el-checkbox v-model="option.checked"></el-checkbox>
											</el-col>
											<el-col v-if="option.isExclusive" :span="8" @click="toggleExclusive">
												<div style="height: 100%; display: flex; align-items: center; cursor: pointer">
													<el-icon v-if="isToggleExclusive" size="18px"><ArrowDown /></el-icon>
													<el-icon v-else size="18px"><ArrowRight /></el-icon>
												</div>
											</el-col>
										</el-row>
									</template>

									<template #append>
										<el-input-number v-model="option.width" size="small" :min="10" :max="1000" :precision="0"> </el-input-number>
									</template>
								</el-input>
								<div v-if="option.isExclusive" v-show="isToggleExclusive">
									<div
										v-for="(eiOption, index) in option.exclusiveArr"
										:key="index"
										style="margin: 6px"
										:style="{
											border: eiOption.label === '' ? '1px solid red' : '1px solid #00ffff',
										}"
									>
										<el-input
											v-model="eiOption.label"
											:class="[{ shake: eiOption.label === '' && shakeAnimation }]"
											size="small"
											maxlength="30"
											show-word-limit
											placeholder="请输入列名，不能为空"
										>
											<template #prepend>
												<el-row style="width: 20px; text-align: center">
													<el-col :span="24">
														<el-checkbox v-model="eiOption.checked"></el-checkbox>
													</el-col>
												</el-row>
											</template>
											<template #append>
												<el-input-number v-model="eiOption.width" size="small" :min="10" :max="1000" :precision="0"> </el-input-number>
											</template>
										</el-input>
									</div>
								</div>
							</div>
						</template>
					</draggable>
				</el-col>
			</el-row>
			<template #footer>
				<el-button class="button-default" size="small" @click="handleReset">重 置</el-button>
				<el-button class="button-default" size="small" @click="dialog.open = false">取 消</el-button>
				<el-button class="button-primary" size="small" @click="handleConfirm">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="CustomColumn" lang="tsx">
import { ArrowDown, ArrowRight } from '@element-plus/icons-vue';
import { ref, reactive, onMounted } from 'vue';

import draggable from 'vuedraggable';
import { randomUUID } from '@/utils/common';
import { getAllCustomDisplayFields } from '@/api/search/searchOptions';

export interface CustomColumnType extends TableColumnType {
	/**序号用于排序 */
	position?: number;
	isChild?: boolean;
}

export interface CustomOptionType {
	/**序号用于排序 */
	position?: number;
	prop: string;
	label?: string;
	checked?: boolean;
	width?: number;
	/**是否有专属指标 */
	isExclusive?: boolean;
	/**专属指标 */
	exclusiveArr?: any[];
}

const props = defineProps<{
	title?: string;
	pageType: string;
}>();

// 弹出层
const dialog = reactive({
	key: randomUUID(),
	open: false,
});
const sign_key = ref('');

// 自定义列的的渲染列表
const options = ref<CustomOptionType[]>();

// 自定义列的map
const optionsMap = ref<Record<string, CustomOptionType>>();

// 表格列数据
const columns = ref<CustomColumnType[]>();
// 抖动动画

const shakeAnimation = ref(false);
// 专属指标集展示开关

//
const isToggleExclusive = ref(false);
const exclusiveArr = ref<any[]>([]);

onMounted(() => {
	document.body.ondrop = (event) => {
		event.preventDefault();
		event.stopPropagation();
	};
});

defineExpose({
	useCustomColumn,
	handleOpen,
});

// 初始化自定义列
function useCustomColumn(sign: string, columns: CustomColumnType[]) {
	console.log('useCustomColumn');
	const oriSign = sign + '._ori';
	let customConfig: Record<string, CustomOptionType> = JSON.parse(window.localStorage.getItem(sign)!);
	let oriCustomConfig: Record<string, CustomOptionType> = JSON.parse(window.localStorage.getItem(oriSign)!);

	new Promise((resolve) => {
		// 查询专属指标集
		getAllCustomDisplayFields(props.pageType).then((res: Record<string, any>) => {
			const eiMap = res.data?.exclusiveIndicator;
			if (eiMap !== undefined && eiMap !== null) {
				for (let k in eiMap) {
					const v = eiMap[k];
					exclusiveArr.value.push({
						prop: k,
						label: v,
						checked: false,
						width: 120,
					});
				}
				// console.log('xclusiveArr', exclusiveArr);
			}
			resolve('');
		});
	}).then(() => {
		// 记录原始列信息
		if (oriCustomConfig === null || oriCustomConfig === undefined) {
			const oriMap: Record<string, CustomOptionType> = {};
			for (let i = 0; i < columns.length; i++) {
				const field = columns[i];
				oriMap[field.prop] = {
					position: i,
					prop: field.prop,
					label: field.label,
					checked: !field.hide,
					width: field.width,
					isExclusive: field.isExclusive,
					exclusiveArr: field.isExclusive ? exclusiveArr.value : undefined,
				};
			}
			window.localStorage.setItem(oriSign, JSON.stringify(oriMap));
			console.log(' useCustomColumn-', oriMap);
		}

		// 同步自定义列
		if (customConfig === null || customConfig === undefined) {
			return;
		}
		syncColumnData(customConfig, columns);
	});
}
// 打开弹出层
function handleOpen(sign: string, columnsData: CustomColumnType[]) {
	console.log('handleopen', columnsData);
	sign_key.value = sign;
	options.value = [];
	columns.value = columnsData;
	let customConfig: Record<string, CustomOptionType> = JSON.parse(window.localStorage.getItem(sign)!);
	if (customConfig instanceof Object === false) {
		customConfig = {};
	}
	for (let i = 0; i < columnsData.length; i++) {
		const field = columnsData[i];
		const customField = customConfig[field.prop];
		if (customField === null || customField === undefined) {
			if (!field.isChild) {
				customConfig[field.prop] = {
					position: i,
					prop: field.prop,
					label: field.label,
					checked: !field.hide,
					width: field.width,
					isExclusive: field.isExclusive,
					exclusiveArr: field.isExclusive ? exclusiveArr.value : undefined,
				};
			}
		}
		if (!field.isChild) {
			options.value.push(customConfig[field.prop]);
		}
	}

	optionsMap.value = customConfig;
	dialog.open = true;
}
// 确认
function handleConfirm() {
	// 校验
	for (let prop in optionsMap.value) {
		const option = optionsMap.value[prop];
		if (option.label === undefined || option.label === null || option.label === '') {
			shakeAnimation.value = true;
			setTimeout(() => {
				shakeAnimation.value = false;
			}, 500);
			return;
		} else if (option.isExclusive) {
			for (let eiOption of option.exclusiveArr!) {
				if (eiOption.label === undefined || eiOption.label === null || eiOption.label === '') {
					shakeAnimation.value = true;
					setTimeout(() => {
						shakeAnimation.value = false;
					}, 500);
					return;
				}
			}
		}
	}
	// 同步自定义列
	if (columns.value === undefined || optionsMap.value === undefined) return;
	syncColumnData(optionsMap.value, columns.value);
	window.localStorage.setItem(sign_key.value, JSON.stringify(optionsMap.value));
	dialog.open = false;
}
/**将自定义列信息同步到表格列
 *@param customConfig 自定义列的配置
 *@param columns 表格列的配置
 * **/

function syncColumnData(customConfig: Record<string, CustomOptionType>, columns: CustomColumnType[]) {
	const columnsLen = columns.length;
	// 给表格列修改hide、position属性，以及专属指标
	for (let i = 0; i < columnsLen; i++) {
		const field = columns[i];
		const customField: CustomOptionType = customConfig![field.prop];
		if (customField !== null && customField !== undefined) {
			field.position = customField.position;
			field.label = customField.label;
			field.hide = !customField.checked;
			field.width = customField.width;
			if (customField.isExclusive && customField.exclusiveArr) {
				// 添加专属指标
				for (let j = 0; j < customField.exclusiveArr.length; j++) {
					const eiCustomField = customField.exclusiveArr[j];
					const eiField = columns.find((column) => column.prop === eiCustomField.prop);
					if (eiField === undefined || eiField === null) {
						columns.push({
							isChild: true,
							position: customField.position,
							prop: eiCustomField.prop,
							label: eiCustomField.label,
							hide: !eiCustomField.checked,
							width: eiCustomField.width,
						});
					} else {
						eiField.isChild = true;
						eiField.position = customField.position;
						eiField.prop = eiCustomField.prop;
						eiField.label = eiCustomField.label;
						eiField.hide = !eiCustomField.checked;
						eiField.width = eiCustomField.width;
					}
				}
			}
		}
	}
	// 重新排序
	columns.sort((a, b) => Number(a.position) - Number(b.position));
}

// 关闭自定义列弹出层
function handlerClosed() {
	dialog.key = randomUUID();
}
// 排序变更
function handleSortChange() {
	// 每次排序变更从头到位重新设置位置
	options.value?.forEach((op, index) => {
		op.position = index;
		if (optionsMap.value !== undefined) {
			optionsMap.value[op.prop].position = index;
		}
	});
}
// 重置
function handleReset() {
	window.localStorage.removeItem(sign_key.value);
	window.localStorage.removeItem(sign_key.value + '._ori');
	window.location.reload();
}
// 切换展开/收起专属指标
function toggleExclusive() {
	isToggleExclusive.value = !isToggleExclusive.value;
	console.log('toggledd');
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.custom-column-container {
	background: #36759c;
}

.custom-table-class {
}

/* 自定义列弹框样式 */

:deep(.custom-table-class) {
	display: flex;
	flex-direction: column;
	margin: 0 !important;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	max-height: calc(100% - 100px);
	max-width: calc(100% - 30px);
	min-width: 650px;
	background: #36759c;
	.el-dialog__body {
		flex: 1;
		overflow: auto;
		margin-right: 7px;
		padding: 5px 20px;
	}
	.el-form-item {
		margin-bottom: 0;
	}
}
:deep(.el-dialog__header .el-dialog__title) {
	background-image: url('@/assets/images/bpm/dialog/init-title.png');
	background-repeat: no-repeat;
	background-position: center;
	background-size: 100% 100%;
	color: #ffffff;
	font-size: 16px;
	display: inline-block;
	width: 140px;
	padding-left: 5px;
}

/*滚动条*/
:deep(::-webkit-scrollbar) {
	width: 10px;
	height: 10px;
}
/*滚动条-轨道*/
:deep(::-webkit-scrollbar-track) {
	border-radius: 10px;
	-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
	background-color: rgba(28, 43, 93, 0.81);
}
/*滚动条-滑块*/
:deep(::-webkit-scrollbar-thumb) {
	border-radius: 8px;
	-webkit-box-shadow: inset 0 0 6px rgb(255, 255, 255);
	background-color: rgba(255, 255, 255, 0.2);
}

.button-default {
	background-color: transparent;
	color: #2beded;
	border: 1px solid #2beded;
}
.button-primary {
	background-color: #00ffff;
	color: #1b2a5a;
	border: 1px solid #2beded;
}

// ==========================================================

:deep(.el-input__wrapper) {
	background: #1c374b;
}

:deep(.el-input-group__prepend) {
	border: 0;
	padding: 0 6px;
	background: var(--el-fill-color-blank) !important;
}

:deep(.el-input-group__append) {
	// background-color: #1c374b;
	border: 0;
	padding: 0;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
	background-color: #1c374b;
	border-color: #61edf4;
}

:deep(.el-input .el-input__count .el-input__count-inner) {
	background: #1c374b;
}

:deep(.el-input-number--mini .el-input-number__increase) {
	background-color: #00ffff;
}
:deep(.el-input-number--mini .el-input-number__decrease) {
	background-color: #00ffff;
}
:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
	background: none;
}

.can-move {
	cursor: move;
	font-size: 16px;
}

.can-expand {
	cursor: pointer;
	font-size: 16px;
}

.drag-cls {
}

.ghost-cls {
	border: 2px dashed #3089dc;
}

.chosen-cls {
	border: 2px dashed #3089dc;
}

/* 抖动动画 */
.shake {
	animation-name: errtips;
	animation-duration: 0.25s;
	animation-iteration-count: infinite;
}
@keyframes errtips {
	0% {
		transform: translateX(1px);
	}
	10% {
		transform: translateX(3px);
	}
	20% {
		transform: translateX(5px);
	}
	30% {
		transform: translateX(3px);
	}
	40% {
		transform: translateX(1px);
	}
	50% {
		transform: translateX(-1px);
	}
	60% {
		transform: translateX(-3px);
	}
	70% {
		transform: translateX(-5px);
	}
	80% {
		transform: translateX(-3px);
	}
	90% {
		transform: translateX(-1px);
	}
	100% {
		transform: translateX(0px);
	}
}
</style>
